package com.xmb.wechat.view.qq;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nil.sdk.utils.DateUtils;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.bean.WechatMsgBean;
import com.xmb.wechat.definterface.HintListener;
import com.xmb.wechat.definterface.SimpleTextWatcher;
import com.xmb.wechat.util.WechatDateFormat;
import com.xmb.wechat.view.alipay.AliPayTransferActivity;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author lijiangop
 * @CreateTime 2020/5/21 09:33
 */
public class QQRedPacketActivity extends BaseActivity {

    @BindView(R2.id.tv_tips)
    TextView       mTvTips;
    @BindView(R2.id.iv_sender)
    ImageView      mIvSender;
    @BindView(R2.id.tv_sender)
    TextView       mTvSender;
    @BindView(R2.id.et_money)
    EditText       mEtMoney;
    @BindView(R2.id.et_remark)
    EditText       mEtRemark;
    @BindView(R2.id.iv_receiver)
    ImageView      mIvReceiver;
    @BindView(R2.id.tv_receiver)
    TextView       mTvReceiver;
    @BindView(R2.id.tv_time)
    TextView       mTvTime;
    @BindView(R2.id.tv_received)
    TextView       mTvReceived;
    @BindView(R2.id.tv_unreceived)
    TextView       mTvUnreceived;
    @BindView(R2.id.re_receiver)
    RelativeLayout mReReceiver;
    @BindView(R2.id.re_time)
    RelativeLayout mReTime;

    private WechatMsgBean     mWechatMsgBean;
    private WechatContactBean mSenderContactBean, mReceiverContactBean;

    public QQRedPacketActivity() {
        super(R.layout.activity_qq_redpacket);
    }

    @Override
    protected void initView() {
        initCurrentData();
        mEtMoney.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChangedFinish(String value) {
                checkMoney(value);
            }
        });
        showExemption(new HintListener() {
            @Override
            public void onConfirm() {
                //do nothing
            }

            @Override
            public void onCancel() {
                QQRedPacketActivity.this.finish();
            }
        });
    }

    private void initCurrentData() {
        //创建一个发送联系人对象
        mSenderContactBean = WechatContactBean.instanceNewQQMe(this);
        //创建一个接收联系人对象
        mReceiverContactBean = new WechatContactBean();
        //创建一个消息对象
        mWechatMsgBean = new WechatMsgBean();
        //默认设置发送人我自己
        WechatContactBean.setupAvatarIntoImageView(mSenderContactBean, mIvSender, 12);
        mTvSender.setText(mSenderContactBean.getName());
        //默认自己发送红包
        mWechatMsgBean.setMoneySenderID(-1);
        //默认已领取红包
        setRedPacketState(true);
        //默认当前时间
        mTvTime.setText(DateUtils.getCurDateByFormat("HH:mm"));
        mWechatMsgBean.setReceiveTime(new Date());
    }

    @OnClick({R2.id.re_sender, R2.id.tv_received, R2.id.tv_unreceived, R2.id.re_receiver, R2.id.re_time, R2.id.btn_preview})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.re_sender) {
            KeyboardUtils.hideSoftInput(this);
            showRoleChooseSender(this, true, 1, true, mineContactBean -> checkAndInitValue(0, mineContactBean));
        } else if (id == R.id.tv_received) {//已领取
            KeyboardUtils.hideSoftInput(this);
            setRedPacketState(true);
        } else if (id == R.id.tv_unreceived) {//未领取
            KeyboardUtils.hideSoftInput(this);
            setRedPacketState(false);
        } else if (id == R.id.re_receiver) {
            KeyboardUtils.hideSoftInput(this);
            showRoleChooseReceiver(this, true, 1, true, mineContactBean -> checkAndInitValue(1, mineContactBean));
        } else if (id == R.id.re_time) {
            KeyboardUtils.hideSoftInput(this);
            @SuppressLint("SimpleDateFormat")
            TimePickerView pvTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调
                mWechatMsgBean.setReceiveTime(date);
                mTvTime.setText(WechatDateFormat.formatRedPacketTime(date, new SimpleDateFormat("MM月dd日 HH:mm")));
            }).setType(new boolean[]{false, true, true, true, true, false})// 默认全部显示
                    .setCancelText("取消")//取消按钮文字
                    .setSubmitText("确定")//确认按钮文字
                    .setTitleSize(20)//标题文字大小
                    .setTitleText("时间")//标题文字
                    .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                    .isCyclic(true)//是否循环滚动
                    .setSubmitColor(getResources().getColor(R.color.wechat_tab_bg_green))//确定按钮文字颜色
                    .setCancelColor(getResources().getColor(R.color.wechat_tab_bg_green))//取消按钮文字颜色
                    .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                    .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .build();
            pvTime.show();
        } else if (id == R.id.btn_preview) {
            doPreview();
        }
    }

    private void doPreview() {
        //发送人
        String sender = mTvSender.getText().toString().trim();
        if (TextUtils.isEmpty(sender)) {
            ToastUtils.showShort("请选择发送人");
            return;
        }
        //红包金额
        String money = mEtMoney.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            ToastUtils.showShort("请输入红包金额");
            return;
        }
        if (!checkMoney(money))
            return;
        if (mWechatMsgBean.isReceiveMoney()) {
            //领取人
            String receiver = mTvReceiver.getText().toString().trim();
            if (TextUtils.isEmpty(receiver) || TextUtils.equals(receiver, "请选择")) {
                ToastUtils.showShort("请选择领取人");
                return;
            }
            //领取时间
            String time = mTvTime.getText().toString().trim();
            if (TextUtils.isEmpty(time)) {
                ToastUtils.showShort("请选择领取时间");
                return;
            }
        }
        String remark = mEtRemark.getText().toString().trim();
        mWechatMsgBean.setMoneyRemark(TextUtils.isEmpty(remark) ? "恭喜发财" : remark);
        QQRedPacketDetailActivity.start(QQRedPacketActivity.this, mSenderContactBean, mReceiverContactBean, mWechatMsgBean);
    }

    /**
     * 设置红包的领取状态
     *
     * @param isReceived
     */
    private void setRedPacketState(boolean isReceived) {
        mTvReceived.setSelected(isReceived);
        mTvUnreceived.setSelected(!isReceived);
        mWechatMsgBean.setReceiveMoney(isReceived);
        //
        mReReceiver.setVisibility(isReceived ? View.VISIBLE : View.GONE);
        mReTime.setVisibility(isReceived ? View.VISIBLE : View.GONE);
    }

    /**
     * 检查输入金额是否符合规则
     *
     * @param str
     */
    private boolean checkMoney(String str) {
        try {
            double m = Double.parseDouble(str);
            if (m < 0.01) {
                mTvTips.setVisibility(View.VISIBLE);
                mTvTips.setText("单个红包金额不能少于0.01元");
            } else {
                mTvTips.setVisibility(View.GONE);
            }
            if (m < 0.01)
                return false;
            mWechatMsgBean.setMoney(m);
            return true;
        } catch (Exception e) {
            ToastUtils.showShort("金额输入有误");
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            if (requestCode == REQUEST_CODE_CHOOSE_OTHER_SEND || requestCode == REQUEST_CODE_CHOOSE_NEW_ADD_SEND) {
                checkAndInitValue(0, result);
            } else if (requestCode == REQUEST_CODE_CHOOSE_OTHER_RECEIVE || requestCode == REQUEST_CODE_CHOOSE_NEW_ADD_RECEIVE) {
                checkAndInitValue(1, result);
            }
        }
    }

    /**
     * 检查选中角色是否可赋值
     *
     * @param type
     * @param mineContactBeam
     */
    private void checkAndInitValue(int type, WechatContactBean mineContactBeam) {
        if (mineContactBeam == null)
            return;
        long mineId = mineContactBeam.getId();
        if (type == 0) {//发送者
            if (mReceiverContactBean != null && mineId == mReceiverContactBean.getId()) {
                ToastUtils.showShort("发送人不能与领取人一样");
                return;
            }
            //赋值
            mSenderContactBean = mineContactBeam;
            //显示界面
            WechatContactBean.setupAvatarIntoImageView(mSenderContactBean, mIvSender, 12);
            mTvSender.setText(TextUtils.isEmpty(mSenderContactBean.getName()) ? "" : mSenderContactBean.getName());
            //设置发送者
            mWechatMsgBean.setMoneySenderID(mineContactBeam.getId());
            //接收人是自己,收红包没有未领取的详情页
            if (mineContactBeam.getId() == -1) {//我发
                mTvUnreceived.setVisibility(View.VISIBLE);
            } else {//不是我发
                mTvUnreceived.setVisibility(View.GONE);
                setRedPacketState(true);
            }
        } else {//接受者
            if (mSenderContactBean != null && mineId == mSenderContactBean.getId()) {
                ToastUtils.showShort("领取人不能与发送人一样");
                return;
            }
            //赋值
            mReceiverContactBean = mineContactBeam;
            //显示界面
            WechatContactBean.setupAvatarIntoImageView(mReceiverContactBean, mIvReceiver, 12);
            mTvReceiver.setText(TextUtils.isEmpty(mReceiverContactBean.getName()) ? "" : mReceiverContactBean.getName());
        }
    }
}
